package org.dawning.shop.order.command.config;

import com.rabbitmq.client.Channel;
import org.axonframework.amqp.eventhandling.spring.SpringAMQPMessageSource;
import org.axonframework.config.SagaConfiguration;
import org.axonframework.serialization.Serializer;
import org.dawning.shop.order.command.saga.OrderSaga;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by Edison on 2017/3/25.
 */
@Configuration
public class AMQPConfiguration {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${axon.amqp.exchange}")
    private String exchangeName;


    @Bean
    public SpringAMQPMessageSource queueMessageSource(Serializer serializer){
        return new SpringAMQPMessageSource(serializer){
            @RabbitListener(queues = {"inventory"})
            @Override
            public void onMessage(Message message, Channel channel) throws Exception {
                logger.debug("message received: "+message.toString());
                super.onMessage(message, channel);
            }
        };
    }


    @Bean
    public SagaConfiguration<OrderSaga> sagaConfiguration(Serializer serializer){
        //sagaConfiguration.registerHandlerInterceptor(c->transactionManagingInterceptor());
        return SagaConfiguration.subscribingSagaManager(OrderSaga.class, c-> queueMessageSource(serializer));
    }

}
